// /pages/goods_cart/index.js
import {
    getReMallShopping
} from "../../api/cart.js"
import {
    getNavigationbar
} from "../../api/index.js"
import {
    Decimal
} from '../../utils/decimal.js'
Page({
    options: {
        styleIsolation: 'shared'
    },
    /**
     * 页面的初始数据
     */
    data: {
        giftHasSelected: false, // 赠品是否显示已抢光
        navTitle: '购物车',
        height: "",
        obj: {},
        isBack: false,
        isEdit: false,
        isAhow: false,
        scrollViewHeight: 0, // 滚动区域高度
        allCheckSelVal: false, // 当前全选状态
        discount: 0,
        currentoffersInfo: {}, // 当前操作的赠送商品
        cartList: [],
        cartTotalPrice: "0.0", // 购物车总价格
        checkGoodsList: [],
        isSpecs: false, // 商品规格弹窗打开状态
        isPopups: false, // 默认弹窗打开状态
        showFooter: false, // 是否显示确认按钮
        popupType: "", // 弹窗类型
        isShow: false,
        addressList: [],
        address: "请选择地址",
        addressId: "",
        zPactive: 1,
        showMian: false,
        showModal: false,
        isSlot: false,
        modalTitle: "",
        message: "",
        confirmText: "",
        cancelText: "",
        showCancelButton: false,
        // 模拟购物车价格变动提示
        price: 0,
        // 模拟购物赠品商品无库存时提示
        kcCount: 0,
        // 模拟购物未选赠品时提示
        zpCount: 0,
        zpList: [

        ],
        changePriceList: [],
        specsDetail: {},
        delCartids: '',
        numbersObj: {}, // 数量操作项
        isNumbers: false // 数量改变弹窗
    },
    handleCancel() {
        this.setData({
            isNumbers: false
        }, () => {
            wx.showTabBar()
        })
    },
    hdleClose() {
        this.setData({
            isAddress: false
        })
    },
    onConfirms() {
        wx.navigateTo({
            url: '/pages/address_management/index',
        })
    },
    handleSubmit() {
        wx.showLoading({
            title: '加载中...',
            mask: true,
        });
        getReMallShopping({
            act: 'carthandle',
            id: this.data.numbersObj.id,
            number: this.data.numbersObj.numbers
        }).then(res => {
            this.setData({
                isNumbers: false,
            }, () => {
                wx.showTabBar()
            })
            if (res) {
                this.getHttpReMallShopping()
                setTimeout(() => {
                    wx.hideLoading();
                }, 1000)
            }
            if (res.result == '101') {
                return getApp().Tips({
                    title: res.msg
                })
            }
        }).catch(err => {
            wx.hideLoading();
        })
    },
    inputNumbers(e) {
        this.setData({
            numbersObj: {
                ...this.data.numbersObj,
                numbers: e.detail.value
            }
        })
    },
    goodsDetail(e) {
        console.log('e', e)
        const params = {
            goodsId: e.currentTarget.dataset.value.productid,
            area: "",
            detailType: 1,
            act: "good_detail"
        }
        wx.navigateTo({
            url: `/pages/goods_detail/index?data=${JSON.stringify(params)}`,
        })
    },
    agentFn(e) {
        let obj = {
            ...e.currentTarget.dataset.supitem,
            show: true,
            RefundStatus: [],
        }
        let objStr = encodeURIComponent(JSON.stringify(obj));
        wx.navigateTo({
            url: '/pages/brand_detail/index?obj=' + objStr,
        })
    },
    calcFn(num1 = 0, num2 = 0) {
        const n1 = new Decimal(num1)
        const n2 = new Decimal(num2)
        const sum = n1.plus(n2)
        return sum.toDecimalPlaces(2).toString()
    },
    subFn(num1 = 0, num2 = 0, fixed = 2) {
        const n1 = new Decimal(num1)
        const n2 = new Decimal(num2)
        const sum = n1.minus(n2)
        return sum.toDecimalPlaces(fixed).toString()
    },
    // 去凑单
    bindIssue(e) {
        console.log('点击')
        let objStr = encodeURIComponent(JSON.stringify({
            ...e.detail,
            isCart: true
        }))
        wx.navigateTo({
            url: `/pages/goods_list/index?obj=${objStr}`
        })
    },

    /**
     * 编辑购物车回调函数方法
     */
    handleEditCart() {
        const state = !this.data.isEdit
        this.setData({
            isEdit: state,
        })
    },
    /**
     * 打开商品规格弹窗回调函数方法
     */
    handleSelSpecs(e) {
        let data = {
            ...e.currentTarget.dataset.value
        }
        //详细接口
        getNavigationbar({
            act: 'good_detail',
            id: data.productid
        }).then(res => {
            data = {
                ...res,
                ...e.currentTarget.dataset.value
            }
            console.log('详细接口', data)
            this.setData({
                specsDetail: data
            })
            if (data.property && data.property.length) {
                this.setData({
                    isSpecs: true
                }, () => {
                    wx.hideTabBar()
                })
            } else {
                return wx.showModal({
                    title: '提示',
                    content: '商品不存在',
                    showCancel: false,
                    success(res) {
                        if (res.confirm) {
                            console.log('用户点击确定')

                        }
                    }
                })

            }

        })
    },
    /**
     * 换促销回调函数方法
     */
    handleSelPromo(e) {
        const {
            type
        } = e.currentTarget.dataset
        const {
            value
        } = e.currentTarget.dataset
        if (value.offers_list) {
            value.offerList = value.offers_list
            value.offerList.forEach(item => {
                item.offerTitle = this.parseTtile(item)

            })
        } else {
            wx.nextTick(() => {
                getApp().Tips({
                    title: "暂无促销活动"
                });
                return
            });
        }

        console.log(value)
        this.setData({
            height: "880rpx",
            popupType: type,
            isPopups: true,
            popupGood: value,
        }, () => {
            wx.hideTabBar()
        })
    },
    /**
     * 促销标题
     */
    parseTtile(value) {
        console.log('====1', value)
        let actstr = ""
        this.data.showMian = true
        value.buy = value.buy.replaceAll(".00", "")
        value.derate = value.derate.replaceAll(".00", "")
        const str = `差${value.difference}元可参加`
        const strNmae = `差${value.difference}件可参加`
        switch (value.type) {
            case "1":
                if (value.buy <= 0) {
                    actstr = `立减${value.derate}元`
                } else {
                    actstr = `${value.can_select==0?str:''}满${value.buy}元减${parseFloat(value.derate)}元`
                }
                break
            case "2":
                if (value.buy <= 0) {
                    actstr = `送${value.derate}件`
                } else {
                    actstr = `${value.can_select==0?str:''}满${value.buy}元送${value.derate}件`
                }
                break
            case "3":
                actstr = `${value.can_select==0?strNmae:''}满${value.buy}件送${value.derate}件`
                break
            case "4":
                if (value.buy <= 1) {
                    actstr = `${value.derate / 10}折`
                } else {
                    actstr = `${value.can_select==0?strNmae:''}满${value.buy}件${value.derate / 10}折`
                }
                break
            case "5":
                if (value.buy <= 0) {
                    actstr = `${value.derate / 10}折`
                } else {
                    actstr = `${value.can_select==0?str:''}满${value.buy}元打${value.derate / 10}折`
                }
                break
            case "6":
                if (value.buy <= 0) {
                    actstr = `立减${value.derate}元`
                } else {
                    actstr = `${value.can_select==0?str:''}满${value.buy}元送${value.derate}元`
                }
                break
        }
        return actstr
    },
    /**
     * 换促销回调函数方法(选择赠品)
     */
    handleSelZp(e) {
        const {
            value,
            cartid
        } = e.currentTarget.dataset
        console.log(value, cartid)
        getReMallShopping({
            act: 'choose_activity',
            other_detail_id: value.id,
            cartid: cartid
        }).then(res => {
            console.log(res)
            this.getHttpReMallShopping()
        })
        this.setData({
            isPopups: false,
            isSpecs: false
        })
        getApp().$showTab()
    },
    /**
     * 更换赠品回调函数方法
     */
    handleReplaceZp(e) {
        const {
            type,
            good,
            item
        } = e.currentTarget.dataset
        if (this.data.showMian == false) {
            return
        }
        let zpSelect = good.gift.reduce((acc, cur) => acc + cur.selected_numbers, 0)
        good.gift.forEach(item => {
            item.isSelected = this.calcFn(item.inventorys, item.selected_numbers)
        })
        // const flag = good.gift.every(item => item.isSelected > 0)
        const flag = good.gift.some(item => item.inventorys > 0 && item.isSelected != '0');
        console.log('good', good)
        this.setData({
            height: "480rpx",
            popupType: type,
            showFooter: true,
            isPopups: true,
            giftHasSelected: flag,
            currentoffersInfo: {
                can_sell: item.can_sell,
                ...good,
                zpSelect,
                cartid: item.id
            },
        })
        getApp().$showTab()
        // this.handleSelSpecs()
    },
    /**
     * 弹窗确认按钮回调函数方法
     */
    handleConfirm(e) {
        console.log("data", e)

        let data
        let type
        if (e.detail) {
            data = e.detail
            type = 'spec'
        } else {
            data = this.data.zpList
            type = 'zp'
        }
        console.log("data", data)
        console.log("type", type)

        if (type == 'spec') {
            getReMallShopping({
                act: 'change_property',
                cart_id: e.detail.data.id,
                propertyid: e.detail.data.propertyid,
                address_id: this.data.addressId

            }).then(res => {
                this.getHttpReMallShopping()
                this.setData({
                    isPopups: false,
                    isSpecs: false
                })
            }).catch(() => {
                this.setData({
                    isPopups: false,
                    isSpecs: false
                })
            })
        } else {

            let giftList = []
            this.data.currentoffersInfo.gift.forEach(item => {
                if (item.selected_numbers) {
                    giftList.push({
                        productid: item.id,
                        numbers: item.selected_numbers
                    })
                }
            })
            // if (giftList.length > 0) {
            getReMallShopping({
                act: 'choose_activity_gifts',
                cart_id: this.data.currentoffersInfo.cartid,
                other_detail_id: this.data.currentoffersInfo.id,
                gift: JSON.stringify(giftList)

            }).then(res => {
                this.setData({
                    isPopups: false,
                })
                if (res.result == '101') {
                    getApp().Tips({
                        title: res.msg
                    })
                } else {
                    this.getHttpReMallShopping()
                }
            })
            // } else {
            //     this.setData({
            //         isPopups: false,
            //     })

            // }
        }
        getApp().$showTab()
    },

    /**
     * 关闭弹窗回调函数方法
     */
    handleClose() {
        this.setData({
            isPopups: false,
            isSpecs: false
        })
        getApp().$showTab()
    },
    /**
     * 提示弹窗确认回调函数方法
     */
    handleModalChange(e) {
        console.log(e)
        const type = e.detail
        if (type == "confirm") {
            const handleType = e.currentTarget.dataset.type
            console.log(handleType)
            if (handleType == 'del') {
                this.delCartGoods()
            } else if (handleType == "goOrder") {
                this.goOrder()
            }
            this.setData({
                showModal: false
            })
        } else {
            this.setData({
                showModal: false
            })
            // getApp().Tips({ title: "操作已取消" })
        }
    },
    /**
     * 
     */
    delCartGoods() {
        getReMallShopping({
            act: 'delgoods',
            cartids: this.data.delCartids
        }).then(res => {
            this.getHttpReMallShopping();
        })
    },
    /**
     * 全选回调函数方法
     * @param {*} e 
     */
    allCheckSelChange(e) {
        this.setData({
            allCheckSelVal: !this.data.allCheckSelVal
        })
        let cartids = []
        this.data.cartList.forEach(item => {
            item.brand_list.forEach(el => {
                el.lists.forEach(k => {
                    cartids.push(k.id)
                })
                el.offers.forEach(j => {
                    j.lists.forEach(s => {
                        cartids.push(s.id)
                    })
                })
            })
            item.mix_offers.forEach(el => {
                el.brand_list.forEach(k => {
                    k.lists.forEach(j => {
                        cartids.push(j.id)
                    })
                })
            })
        })
        wx.showLoading({
            title: '加载中...',
            mask: true,
        });

        getReMallShopping({
            act: 'handle_cartsgoods',
            cartids: cartids.join(),
            flag: this.data.allCheckSelVal ? 1 : 2
        }).then(res => {
            setTimeout(() => {
                wx.hideLoading();
            }, 1000)
            if (res) {

                this.getHttpReMallShopping()
            }
        }).catch(err => {
            setTimeout(() => {
                wx.hideLoading();
            }, 1000)
        })
    },

    /**
     * 供应商选中回调函数方法
     * @param {*} e 
     */
    supCheckSelChange(e) {
        let cartids = []
        const currentItem = e.target.dataset.supitem // 当前选中的项
        currentItem.brand_list.forEach(item => {
            item.lists.forEach(el => {
                cartids.push(el.id)
            })
            item.offers.forEach(j => {
                j.lists.forEach(s => {
                    cartids.push(s.id)
                })
            })
        })
        currentItem.mix_offers.forEach(el => {
            el.brand_list.forEach(k => {
                k.lists.forEach(j => {
                    cartids.push(j.id)
                })
            })
        })
        const flag = !currentItem.is_selected
        wx.showLoading({
            title: '加载中...',
            mask: true,
        });
        getReMallShopping({
            act: 'handle_cartsgoods',
            cartids: cartids.join(),
            flag: flag ? 1 : 2
        }).then(res => {
            setTimeout(() => {
                wx.hideLoading();
            }, 1000)
            if (res) {
                this.getHttpReMallShopping()
            }
        }).catch(err => {
            setTimeout(() => {
                wx.hideLoading();
            }, 1000)
        })
    },

    /**
     * 品牌选中回调函数方法
     * @param {*} e 
     */
    brandCheckSelChange(e) {
        let cartids = []
        const currentItem = e.target.dataset.value
        currentItem.lists.forEach(item => {
            cartids.push(item.id)
        })
        currentItem.offers?.forEach(item => {
            item.lists.forEach(el => {
                cartids.push(el.id)
            })
        })
        const flag = !currentItem.is_selected
        wx.showLoading({
            title: '加载中...',
            mask: true,
        });
        getReMallShopping({
            act: 'handle_cartsgoods',
            cartids: cartids.join(),
            flag: flag ? 1 : 2
        }).then(res => {
            setTimeout(() => {
                wx.hideLoading();
            }, 1000)
            if (res) {
                this.getHttpReMallShopping()
            }
        }).catch(err => {
            setTimeout(() => {
                wx.hideLoading();
            }, 1000)
        })
    },


    /**
     * 商品选中回调函数方法
     * @param {*} e 
     */
    goodsCheckSelChange(e) {
        console.log('e', e)
        const flag = !(e.target.dataset.goods.is_selected - 0)
        wx.showLoading({
            title: '加载中...',
            mask: true,
        });
        if (flag == true) {
            this.data.showMian = true
        } else {
            this.data.showMian = false
        }
        console.log('this.data.allCheckSelVal', flag)
        getReMallShopping({
            act: 'handle_cartsgoods',
            cartids: e.target.dataset.goods.id,
            flag: flag ? 1 : 2
        }).then(res => {
            setTimeout(() => {
                wx.hideLoading();
            }, 1000)
            if (res) {
                this.getHttpReMallShopping()
            }
        }).catch(err => {
            setTimeout(() => {
                wx.hideLoading();
            }, 1000)
        })
    },

    changeVal() {},

    /**
     * 商品数量变化回调函数方法
     * @param {*} e 
     */
    handleNumChange(e) {
        let currentType = e.currentTarget.dataset.type
        let index = e.currentTarget.dataset.value // 获取当前商品下标
        let count = e.currentTarget.dataset.numbers
        if (currentType === '+') {
            count++
        } else if (currentType === '-') {
            count--
        } else {
            this.setData({
                isNumbers: true,
                numbersObj: e.currentTarget.dataset.item
            }, () => {
                wx.hideTabBar()
            })
            return
        }
        wx.showLoading({
            title: '加载中...',
            mask: true,
        });
        getReMallShopping({
            act: 'carthandle',
            id: index,
            number: count
        }).then(res => {
            if (res) {
                this.getHttpReMallShopping()
                setTimeout(() => {
                    wx.hideLoading();
                }, 1000)
            }
            if (res.result == '101') {
                return getApp().Tips({
                    title: res.msg
                })
            }
        }).catch(err => {
            setTimeout(() => {
                wx.hideLoading();
            }, 1000)
        })
    },

    /**
     * 赠品数量
     */
    handlezpNumChange(e) {
        const {
            value
        } = e.currentTarget.dataset
        let num = e.detail
        let total = 0
        this.data.currentoffersInfo.gift.forEach(item => {
            if (item.id != value.id) {
                total += item.selected_numbers
            }
        })
        if (total + num > this.data.currentoffersInfo.derate) {
            wx.showToast({
                title: `已选满${this.data.currentoffersInfo.derate}赠品`,
                icon: 'none',
                duration: 2000
            })
            return
        }
        this.data.currentoffersInfo.gift.forEach(item => {
            if (item.id == value.id) {
                item.selected_numbers = num
            }
        })
        this.setData({
            currentoffersInfo: this.data.currentoffersInfo,
            'currentoffersInfo.zpSelect': total + num
        })
    },

    /**
     * 前往支付回调函数方法
     */
    handleToPay(e) {
        const {
            value
        } = e.currentTarget.dataset
        let flag = this.data.cartList.some(item => item.is_selected === 1)
        let cartids = []
        this.data.cartList.forEach(item => {
            item.brand_list.forEach(el => {
                el.lists.forEach(k => {
                    if (k.is_selected) cartids.push(k.id)
                })
                el.offers.forEach(j => {
                    j.lists.forEach(s => {
                        if (s.is_selected) cartids.push(s.id)
                    })
                })
            })
            item.mix_offers.forEach(el => {
                el.brand_list.forEach(k => {
                    k.lists.forEach(j => {
                        if (j.is_selected) cartids.push(j.id)
                    })
                })
            })
        })

        if (value) {
            // 未选择需删除商品时返回用户提示
            if (!flag) return getApp().Tips({
                title: '请选择需要删除的商品！'
            })

            this.setData({
                showModal: true,
                modalTitle: "删除商品",
                isSlot: false,
                message: "当前操作将做商品删除处理！是否继续执行？",
                confirmText: "确认",
                cancelText: "取消",
                showCancelButton: true,
                delCartids: cartids.join(),
                modalType: 'del',
            })
        } else {
            // 未选择商品时返回用户提示
            if (!flag) return getApp().Tips({
                title: '请选择商品！'
            })

            // if (this.data.zpCount <= 0) {
            //     this.setData({
            //         showModal: true,
            //         modalTitle: "未选赠品",
            //         isSlot: false,
            //         message: "您已满足活动条件，但尚未选择赠品！是否继续支付？",
            //         confirmText: "确认",
            //         cancelText: "取消",
            //         showCancelButton: true,
            //         modalType: "goPay"

            //     })
            // }
            for (const item of this.data.cartList) {
                if (item.is_selected) {
                    let sendprice = item.logistics.sendprice ?? 0
                    let total = item.logistics.total ?? 0
                    if (total < sendprice) {
                        wx.showModal({
                            title: '',
                            showCancel: false,
                            confirmText: '我知道了',
                            content: `${item.agent_name} 所选商品未满足起送￥${sendprice}, 请检查`,
                            confirmColor: '#1A191E'
                        })
                        return
                    }
                }
            }
            console.log('測', this.data.cartList)

            let check = this.data.cartList
            // let noinventory =fa
            let notchoose = true;
            let notcse = true;
            let notcseasa = true;
            let notlecseasa = true;
            let viewText = ''
            check.forEach(element => {
                element.mix_offers.forEach(max => {
                    if (max.is_selected == 1) {
                        if (((max.offers_info.type == 2 || max.offers_info.type == 3) && max.offers_info.can_select) == true) {
                            let hasSelectedNumbers = false;
                            let hasSeedNumbers = false;
                            max.offers_info.gift.forEach(min => {
                                if (min.selected_numbers > 0) {
                                    hasSelectedNumbers = true;
                                }
                                if (min.selected_numbers > 0) {
                                    hasSelectedNumbers = true;
                                }
                            });
                            if (!hasSelectedNumbers) {
                                notchoose = false;
                            } else {
                                notchoose = true;
                            }
                        }
                    }
                });
                element.brand_list.forEach(lin => {
                    if (lin.is_selected == 1) {
                        lin.lists.forEach(awx => {
                            if (awx.offers_info != null) {
                                if (((awx.offers_info.type == 2 || awx.offers_info.type == 3) && awx.offers_info.can_select) == true) {
                                    let hasSelectedNumbers = false;
                                    awx.offers_info.gift.forEach(min => {
                                        if (min.selected_numbers > 0) {
                                            hasSelectedNumbers = true;
                                        }
                                    });
                                    if (!hasSelectedNumbers) {
                                        notcse = false;
                                    } else {
                                        notcse = true;
                                    }
                                    let hasSeleumbers = false;
                                    awx.offers_info.gift.forEach(min => {

                                        if (min.inventorys > 0) {
                                            hasSeleumbers = true;
                                        } else {
                                            if(min.selected_numbers > 0) {
                                                viewText = min.name
                                            }
                                        }
                                    });
                                    if (!hasSeleumbers) {
                                        notlecseasa = false;
                                     
                                    } else {

                                        notlecseasa = true;
                                    }
                                }
                            }

                        });
                        lin.offers.forEach(awx => {
                            if (awx.offers_info != null) {
                                if (((awx.offers_info.type == 2 || awx.offers_info.type == 3) && awx.offers_info.can_select) == true) {
                                    let hasSelectedNumbers = false;

                                    awx.offers_info.gift.forEach(min => {
                                        if (min.selected_numbers > 0) {
                                            hasSelectedNumbers = true;
                                        }

                                    });
                                    let hasSeleumbers = false;
                                    awx.offers_info.gift.forEach(min => {

                                        if (min.inventorys > 0) {
                                            hasSeleumbers = true;
                                        }else {
                                            if(min.selected_numbers > 0) {
                                                viewText = min.name
                                            }
                                        }
                                        
                                    });
                                    if (!hasSelectedNumbers) {
                                        notcseasa = false;
                                    } else {

                                        notcseasa = true;
                                    }
                                    if (!hasSeleumbers) {
                                        notlecseasa = false;
                                    } else {

                                        notlecseasa = true;
                                    }
                                }
                            }

                        });

                    }

                });
            });


            console.log('ssssss', notchoose)
            for (let i = 0; i < check.length; i++) {
                if (check[i].gift && check[i].gift.length > 0) {
                    for (let j = 0; j < check[i].gift.length; j++) {
                        if (check[i].gift[j].inventorys == 0) {
                            noinventory.push(check[i].gift[j].name)
                        } else {
                            if (check[i].gift[j].selected_numbers == 0) {
                                notchoose.push(check[i].gift[j].name)
                            }
                        }
                    }
                }
            }
            if (notlecseasa == false) {
                console.log('viewText',viewText)
                let that = this
                wx.showModal({
                    title: '库存不足',
                    content: '赠品['+viewText+']已无库存，请重新选择赠品或清空赠品继续下单？',
                    showCancel: true, // 是否显示取消按钮，设为false表示不显示
                    confirmText: '确定', // 确定按钮的文本
                    success(res) {
                        if (res.confirm) {
                            that.goOrder()
                        }
                    }
                });
                return
            }
            // console.log('測試',notchoose, noinventory)
            // if (noinventory.length > 0) {
            //     let names
            //     if (noinventory.length <= 3) {
            //         names = noinventory.join("，")
            //     } else {
            //         names = noinventory.slice(0, 3).join("，") + "..."

            //     }

            //     let that = this
            //     wx.showModal({
            //         title: '库存不足',
            //         content:"赠品【" + names + "】已无库存，请重新选择赠品或清空赠品继续下单",
            //         showCancel: true, // 是否显示取消按钮，设为false表示不显示
            //         confirmText: '确定', // 确定按钮的文本
            //         success(res) {
            //             if (res.confirm) {
            //                 that.goOrder()
            //             }
            //         }
            //     });
            // } else
            if (notchoose == false) {
                let that = this
                wx.showModal({
                    title: '提示',
                    content: '存在已满足的满赠活动但并未选择，是否继续下单？',
                    showCancel: true, // 是否显示取消按钮，设为false表示不显示
                    confirmText: '确定', // 确定按钮的文本
                    success(res) {
                        if (res.confirm) {
                            that.goOrder()
                        }
                    }
                });
            } else if (notcse == false) {
                let that = this
                wx.showModal({
                    title: '提示',
                    content: '存在已满足的满赠活动但并未选择，是否继续下单？',
                    showCancel: true, // 是否显示取消按钮，设为false表示不显示
                    confirmText: '确定', // 确定按钮的文本
                    success(res) {
                        if (res.confirm) {
                            that.goOrder()
                        }
                    }
                });
            } else if (notcseasa == false) {
                let that = this
                wx.showModal({
                    title: '提示',
                    content: '存在已满足的满赠活动但并未选择，是否继续下单？',
                    showCancel: true, // 是否显示取消按钮，设为false表示不显示
                    confirmText: '确定', // 确定按钮的文本
                    success(res) {
                        if (res.confirm) {
                            that.goOrder()
                        }
                    }
                });
            } else {
                this.goOrder()
            }



        }
    },
    goOrder() {
        // 前往支付订单页面执行支付请求
        let count = this.data.checkGoodsList.length
        let data = {
            addressId: this.data.addressId,
            totalNumbers: count,
            type: 'cart'
        }
        let objStr = JSON.stringify(data);

        wx.navigateTo({
            url: '/subpackages/pages/confirm_order_shipping/index?data=' + objStr
        })
    },
    /**
     * 删除购物车商品回调函数方法
     * @param {*} e 
     */
    handleDelCartGoods(e) {
        const {
            value
        } = e.currentTarget.dataset // 获取需的删除当前商品数据
        console.log(value)
        this.setData({
            showModal: true,
            modalTitle: "删除商品",
            isSlot: false,
            message: "当前操作将做商品删除处理！是否继续执行？",
            confirmText: "确认",
            cancelText: "取消",
            showCancelButton: true,
            modalType: 'del',
            delCartids: value.id
        })
    },
    /**
     * 计算页面可滚动区域的动态高度
     */
    computeScrollViewHeight() {
        let that = this
        let query = wx.createSelectorQuery().in(this)
        query.select('.content').boundingClientRect()
        query.exec(res => {
            // 滚动区域高度
            that.setData({
                scrollViewHeight: res[0].height
            })
        })
    },

    /**
     * 获取购物车展示列表
     * @param {*} address_id //商品id 
     */
    getHttpReMallShopping() {
        console.log('初始化')
        console.log(this.data.addressId)
        getReMallShopping({
            act: 'cart_list',
            address_id: this.data.addressId,
        }).then(res => {

            console.log('获取购物车展示列表', res)
            if (res) {
                let checkedCartids = [] // 已选中的商品
                let cartids = [] // 购物车商品
                //促销数据整理
                res.lists.forEach(item => {
                    if (item.logistics.sendprice > item.logistics.total) {
                        item.needMoney = this.subFn(item.logistics.sendprice, item.logistics.total, 1)
                    }
                    //混合促销
                    if (item.mix_offers.length > 0) {
                        item.mix_offers.forEach(mix => {
                            let offerGiftCount = 0
                            mix.offers_info.offerTitle = this.parseTtile(mix.offers_info)
                            mix.is_selected = mix.is_selected - 0
                            mix.brand_list.forEach(brand => {
                                brand.is_selected = brand.is_selected - 0
                                brand.lists.forEach(good => {
                                    cartids.push(good.id)
                                    good.is_selected = good.is_selected - 0
                                    if (good.is_selected) checkedCartids.push(good.id)
                                    good.activetypeText = ['', '单品促销', '品牌促销', '混拼促销'][+good.activetype]
                               
                                })
                            })
                            mix.offers_info?.gift && mix.offers_info.gift?.forEach(m => {
                                offerGiftCount += m.selected_numbers
                            })
                            mix.offers_info.offerGiftCount = offerGiftCount
                        })
                    }
                    if (item.brand_list.length > 0) {
                        //品牌促销
                        item.brand_list.forEach(brand => {
                            brand.is_selected = brand.is_selected - 0
                            brand.lists.forEach(el => {
                                el.is_selected = el.is_selected - 0
                                cartids.push(el.id)
                                console.log('good.is_selected ', el.is_selected)
                                if (el.is_selected > 0) checkedCartids.push(el.id)
                                el.activetypeText = ['', '单品促销', '品牌促销', '混拼促销'][+el.activetype]

                                if (el.offers_info !== null) {
                                    el.offers_info.offerTitle = this.parseTtile(el.offers_info)
                                }
                                if (el.is_selected > 0) {
                                    this.data.showMian = true
                                }
                            })
                            brand.offers.forEach(off => {
                                let offerGiftCount = 0
                                off.is_selected = off.is_selected - 0
                                off.offers_info.offerTitle = this.parseTtile(off.offers_info)
                                off.offers_info?.gift && off.offers_info.gift?.forEach(m => {
                                    offerGiftCount += m.selected_numbers
                                })
                                off.offers_info.offerGiftCount = offerGiftCount
                                off.lists.forEach(o => {
                                    cartids.push(o.id)
                                    o.is_selected = o.is_selected - 0
                                    if (o.is_selected) checkedCartids.push(o.id)
                                    o.activetypeText = ['', '单品促销', '品牌促销', '混拼促销'][+o.activetype]
                                })
                            })
                        })
                    }
                })
                const total = res.lists.reduce((acc, cur) => this.calcFn(acc, cur.total), 0)
                const discount = res.lists.reduce((acc, cur) => this.calcFn(acc, cur.discount), 0)
                const cartTotalPrice = this.subFn(total - discount) // 优惠价
                console.log('cartids', cartids, "checkedCartids", checkedCartids)
                const allCheckSelVal = !!cartids.length && checkedCartids.length && cartids.length === checkedCartids.length

                console.log('res.lists', res.lists, res.change_price)
                this.setData({
                    cartList: res.lists,
                    cartTotalPrice,
                    discount,
                    changePriceList: res.change_price,
                    showModal: res.change_price.length > 0,
                    modalTitle: "购物车价格变动提醒",
                    isSlot: true,
                    confirmText: "我知道了",
                    allCheckSelVal
                }, () => {
                    this.computeScrollViewHeight()
                })
            }
        })
    },
    /**
     * 头部导航左侧内容点击回调函数方法
     */
    handleSelAddress() {
        wx.nextTick(() => {
            this.setData({
                isAddress: true,
            })
        })

    },
    getAddress() {

        if (this.data.obj.shop_status == 0 || this.data.obj.shop_status == 1) {
            this.setData({
                isAhow: true,
            })
            return
        }
        getNavigationbar({
            act: "addressres",
            type: "getlist",
        }).then(res => {
            if (res) {
                res.forEach(item => {
                    item.userAddress = item.province + item.city + item.county + item.address
                })
                let addr = res.find(item => item.is_default == "1")
                wx.nextTick(() => {
                    this.setData({
                        addressList: res,
                        address: addr?.userAddress,
                        addressId: addr?.id
                    })
                    this.getHttpReMallShopping();
                })
            }
        })

    },
    check(e) {

        console.log(e)
        const data = e.detail
        let value = e.detail
        getNavigationbar({
            act: "addressres",
            type: "editor",
            id: value.id,
            truename: value.truename,
            phone: value.phone,
            province: value.province,
            city: value.city,
            county: value.county,
            town: value.town,
            provinceId: value.provinceId,
            cityId: value.cityId,
            countyId: value.countyId,
            townId: value.townId,
            address: value.address,
            is_default: '1'
        }).then(res => {
            console.log('切换地方', res)
            if (res) {
                if (res.result == 101) {
                    wx.nextTick(() => {
                        getApp().Tips({
                            title: res.msg
                        });
                    });
                } else {
                    let title = '添加成功';
                    if (value.id) {
                        title = '编辑成功';
                    }
                    this.setData({
                        isShow: false,
                        isAddress: false,
                        address: e.detail.userAddress,
                        address: e.detail.userAddress
                    })
                    wx.showTabBar()
                    this.onLoad()
                    this.getAddress()
                }
            }
        })
        this.setData({
            isAddress: false,
            address: data.userAddress,
            addressId: data.id
        })
        this.getHttpReMallShopping()

    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let res = wx.getStorageSync('USER')
        this.data.obj = res

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getAddress()
        // this.computeScrollViewHeight();

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})